//
//  FDMSearchBarViewController.m
//  Entertainment
//
//  Created by dllo on 16/4/25.
//  Copyright © 2016年 付冬梅. All rights reserved.
//

#import "FDMSearchBarViewController.h"
#import "FDMSearchCollectionViewCell.h"
#import "FDMSearchCollectionReusableView.h"
#import "FDMSearchDetailViewController.h"
#import "FDMSearchTableViewCell.h"
#import "FDMSearchTableSectionHeaderView.h"
#import "FDMSearchTableViewModel.h"
#import "FDMSearchTableViewCellWithImage.h"

@interface FDMSearchBarViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, UICollectionViewDelegateFlowLayout, CleanButtonDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *searchBoxesArr;/**< 搜索范围 */

@property (nonatomic, retain) NSMutableArray *searchHistroyArr;/**< 搜索历史 */
@property (nonatomic, retain) NSMutableArray *searchResultsArr;/**< 搜索结果 */
@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, retain) FDMBaseCollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *dataArr;

@property (nonatomic, retain) FDMBaseTableView *searchTableView;/**< 创建搜索结果tableView */

@property (nonatomic, retain) NSMutableArray *albumResultListModelArr;/**< 搜索结果Image数组 */
@property (nonatomic, retain) NSMutableArray *queryResultList;/**< 搜索结果数组 */
@property (nonatomic, retain) NSDictionary *searchResultDic;/**< 搜索结果字典 */

@end

@implementation FDMSearchBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createView];
    
    [self createCollectionView];
    [self createTableView];
    self.searchTableView.hidden = YES;
    [self searchBarDataHandle];
    
    self.navigationController.navigationBar.hidden = YES;
    self.searchHistroyArr = [NSMutableArray array];
    self.dataArr = [NSMutableArray array];
    
    
    
}

- (void)dealloc {
    [self.searchBar release];
    [self.searchHistroyArr release];
    [self.collectionView release];
    [self.dataArr release];
    [super dealloc];
}

#pragma mark - 创建搜索栏及设置其属性
- (void)createView {
    FDMBaseView *searchView = [[FDMBaseView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:searchView];
    [searchView release];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 15, SCREEN_WIDTH - 80, 40)];
    self.searchBar.showsCancelButton = NO;
    self.searchBar.delegate = self;
    self.searchBar.backgroundColor = [UIColor whiteColor];
    [searchView addSubview:self.searchBar];
    self.searchBar.clearsContextBeforeDrawing = YES;
    self.searchBar.placeholder = @"搜索声音、专辑、主播";
    self.searchBar.tintColor = [UIColor grayColor];
    self.searchTableView.tableHeaderView = searchView;

    FDMBaseButton *cancleButton = [FDMBaseButton buttonWithType:UIButtonTypeCustom];
    cancleButton.frame = CGRectMake(SCREEN_WIDTH - 60, 20, 50, 30);
    [searchView addSubview:cancleButton];
    [cancleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    cancleButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    cancleButton.backgroundColor = [UIColor whiteColor];
    cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];
    cancleButton.layer.cornerRadius = 5;
    cancleButton.layer.masksToBounds = YES;
    [cancleButton addTarget:self action:@selector(cancleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}

// 取消按钮动作
- (void)cancleButtonAction:(FDMBaseButton *)cancleButton {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 创建collectionView
- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 42) / 3, 20);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionView = [[FDMBaseCollectionView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 113) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    [self.collectionView release];
    [self.collectionView registerClass:[FDMSearchCollectionViewCell class] forCellWithReuseIdentifier:@"FDMSearchCollectionViewCell"];
    [self.collectionView registerClass:[FDMSearchCollectionViewCell class] forCellWithReuseIdentifier:@"FDMSearchCollectionViewCellSectionZero"];
    [self.collectionView registerClass:[FDMSearchCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FDMSearchCollectionReusableView"];
}

#pragma mark - collectionViewDelegate
// collectionView分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (self.searchHistroyArr.count == 0) {
        return 1;
    }
    return 2;
}

// collectionView头视图大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(SCREEN_WIDTH, 40);
}

// collectionView每个分区cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        if (self.searchHistroyArr.count == 0) {
            return self.dataArr.count;
        }
        return self.searchHistroyArr.count;
    }
    return self.dataArr.count;
}

// collectionView头视图赋值
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    FDMSearchCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FDMSearchCollectionReusableView" forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        if (self.searchHistroyArr.count == 0) {
            header.titleLabel.text = @"热门搜索";
            header.cleanButton.hidden = YES;
            return header;
        }
        header.titleLabel.text = @"搜索历史";
        header.cleanButton.hidden = NO;
        header.cleanDelegate = self;
        return header;
    }
    if (indexPath.section == 1) {
        header.titleLabel.text = @"热门搜索";
        header.cleanButton.hidden = YES;
        return header;
    }
    return header;
}

// collectionView的cell赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FDMSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMSearchCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        if (self.searchHistroyArr.count == 0) {
            cell.titleLabel.text = self.dataArr[indexPath.row];
            return cell;
        }
        cell.titleLabel.text = self.searchHistroyArr[indexPath.row];
        return cell;
    }
    cell.titleLabel.text = self.dataArr[indexPath.row];
    return cell;
}

// collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    FDMSearchCollectionViewCell *cell = (FDMSearchCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (![self.searchHistroyArr containsObject:cell.titleLabel.text]) {
        [self.searchHistroyArr insertObject:cell.titleLabel.text atIndex:0];
    }
    
    self.searchBar.text = cell.titleLabel.text;
    [self.collectionView reloadData];
    
    FDMSearchDetailViewController *searchDetail = [[FDMSearchDetailViewController alloc] init];
    searchDetail.titleStr = cell.titleLabel.text;
    [self.navigationController pushViewController:searchDetail animated:YES];
    [searchDetail release];
}

#pragma mark - 清除历史记录协议方法实现
- (void)clickCleanButton {
    [self.searchHistroyArr removeAllObjects];
    [self.collectionView reloadData];
}

#pragma mark - searchBarDelegate
// 视图即将出现时隐藏导航栏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

// 检测searchBar内输入文字变化时
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    self.searchTableView.hidden = NO;
    
    if ([self.searchBar.text isEqualToString:@""]) {
        self.searchTableView.hidden = YES;
        [self.searchTableView reloadData];
        [self.collectionView reloadData];
    }
    [self searchBarDataHandle];
    
}

// 输入键盘搜索按钮点击之后
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    FDMSearchDetailViewController *detailViewController = [[FDMSearchDetailViewController alloc] init];
    detailViewController.titleStr = self.searchBar.text;
    if (![self.searchResultsArr containsObject:self.searchBar.text]) {
        [self.searchResultsArr insertObject:self.searchBar.text atIndex:0];
    } else {
        
    }
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    
    [detailViewController release];
}

// 搜索列表点击之后
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"ssss");
    
}

// 搜索文本输入之后
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    [self.searchHistroyArr insertObject:self.searchBar.text atIndex:0];
    if (self.searchHistroyArr.count) {
        [self.collectionView reloadData];
    }
    
}

#pragma mark - 创建tableView
- (void)createTableView {
    self.searchTableView = [[FDMBaseTableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 113) style:UITableViewStylePlain];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    [self.view addSubview:self.searchTableView];
    [self.searchTableView release];
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.searchTableView.separatorColor = [UIColor grayColor];
    [self.searchTableView registerClass:[FDMSearchTableViewCellWithImage class] forCellReuseIdentifier:@"FDMSearchTableViewCellWithImage"];
    
    [self.searchTableView registerClass:[FDMSearchTableViewCell class] forCellReuseIdentifier:@"FDMSearchTableViewCell"];
}
//
//- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
//    self.searchResultsArr = [NSMutableArray array];
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchController.searchBar.text];
//    
//    self.searchResultsArr = [[self.searchBoxesArr filteredArrayUsingPredicate:predicate] mutableCopy];
//    
//    [self.searchTableView reloadData];
//}
//

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 80;
    } else {
        return 40;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.albumResultListModelArr.count;
    }
    return self.queryResultList.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        FDMSearchTableViewCellWithImage *cell = [tableView dequeueReusableCellWithIdentifier:@"FDMSearchTableViewCellWithImage"];
             FDMSearchTableViewModel *model = self.albumResultListModelArr[indexPath.row];
        if (self.albumResultListModelArr.count) {
            NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:model.keyword];
            [attributed addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:20]} range:[model.keyword rangeOfString:self.searchBar.text]];
            cell.titleLabel.attributedText = attributed;
            cell.subtitleLabel.text = model.category;
            [cell.titleImage sd_setImageWithURL:[NSURL URLWithString:model.imgPath] placeholderImage:PLACEHOLDER_IMAGE];
            return cell;
        }
        
    }
    if (indexPath.section == 1) {
        FDMSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FDMSearchTableViewCell"];
            FDMSearchTableViewModel *model = self.queryResultList[indexPath.row];
            if (self.queryResultList.count) {
                NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:model.keyword];
                [attributed addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:20]} range:[model.keyword rangeOfString:self.searchBar.text]];
                cell.titleLabel.attributedText = attributed;
                return cell;
            }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FDMSearchDetailViewController *detailViewController = [[FDMSearchDetailViewController alloc] init];
    if (indexPath.section == 0) {
        FDMSearchTableViewCellWithImage *cell = (FDMSearchTableViewCellWithImage *)[tableView cellForRowAtIndexPath:indexPath];
        if (![self.searchResultsArr containsObject:cell.titleLabel.text]) {
            [self.searchResultsArr insertObject:cell.titleLabel.text atIndex:0];
        }
        detailViewController.titleStr = cell.titleLabel.text;
    }
    if (indexPath.section == 1) {
        FDMSearchTableViewCell *cell = (FDMSearchTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (![self.searchResultsArr containsObject:cell.titleLabel.text]) {
            [self.searchResultsArr insertObject:cell.titleLabel.text atIndex:0];
        }
        detailViewController.titleStr = cell.titleLabel.text;
    }
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    
}

#pragma mark - 数据处理
- (void)searchBarDataHandle {
    // collectionView的数据
    [APPTools GETWithURL:@"http://mobile.ximalaya.com/s/hot_search_key?size=9" par:nil success:^(id responseObject) {
        self.dataArr = responseObject[@"list"];
        [self.collectionView reloadData];
    } failed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
    [APPTools GETWithURL:[NSString stringWithFormat:@"http://search.ximalaya.com/suggest?kw=%@", self.searchBar.text] par:nil success:^(id responseObject) {
        self.searchResultDic = responseObject;
//        if (self.albumResultListModelArr.count || self.queryResultList.count) {
//            
//        }
        self.albumResultListModelArr = [FDMSearchTableViewModel baseModelHandelWithArray:responseObject[@"albumResultList"]];
        self.queryResultList = [FDMSearchTableViewModel baseModelHandelWithArray:responseObject[@"queryResultList"]];
        [self.searchTableView reloadData];
    } failed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
